package com.xh.one2one.knowledgeSystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xh.bussiness.tiku.bean.dto.KnowledgeDto;
import com.xh.bussiness.tiku.bean.request.KnowledgeRequest;
import com.xh.bussiness.tiku.bean.request.QuestionImportLogRequest;
import com.xh.bussiness.tiku.model.QuestionImportLog;
import com.xh.bussiness.tiku.service.IKnowledgeService;
import com.xh.bussiness.tiku.service.IQuestionImportLogService;
import com.xh.bussiness.tiku.service.IQuestionService;
import com.xh.one2one.knowledgeSystem.bean.dto.KnowledgeManagerDto;
import com.xh.one2one.knowledgeSystem.bean.request.KnowledgeManagerRequest;
import com.xh.one2one.knowledgeSystem.model.KnowledgeContent;
import com.xh.one2one.knowledgeSystem.model.KnowledgeManager;
import com.xh.one2one.knowledgeSystem.dao.KnowledgeManagerMapper;
import com.xh.one2one.knowledgeSystem.model.KnowledgeManagerElementRelation;
import com.xh.one2one.knowledgeSystem.service.IKnowledgeContentService;
import com.xh.one2one.knowledgeSystem.service.IKnowledgeManagerElementRelationService;
import com.xh.one2one.knowledgeSystem.service.IKnowledgeManagerService;
import com.xh.core.service.impl.BaseServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.xh.core.bean.XhPage;
import com.xh.core.util.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringJoiner;
import java.util.stream.Collectors;

/**
 * <p>
 * 知识元管理 服务实现类
 * </p>
 *
 * @author tw
 * @since 2020-12-22
 */
@Service
public class KnowledgeManagerServiceImpl extends BaseServiceImpl<KnowledgeManagerMapper, KnowledgeManager> implements IKnowledgeManagerService {

    @Autowired
    private IKnowledgeContentService knowledgeContentService;
    @Autowired
    private IKnowledgeService knowledgeService;
    @Autowired
    private IKnowledgeManagerElementRelationService knowledgeManagerElementRelationService;
    @Autowired
    private IQuestionImportLogService questionImportLogService;
    @Autowired
    private IQuestionService questionService;

    @Override
    public XhPage queryKnowledgeManagerPage(XhPage page, KnowledgeManagerRequest bean) {

        XhPage<KnowledgeManagerDto> selectPage = this.dao.queryByPage(page, bean);
        if(selectPage.getRecords().size() > 0){
            //查询试题和变式题
            List<Integer> types = new ArrayList<>();
            types.add(4);
            types.add(8);

            List<KnowledgeManagerDto> records = selectPage.getRecords();
            for (int i = 0; i < records.size(); i++) {
                 KnowledgeManagerDto dto = records.get(i);
                //查询题目数
                QueryWrapper<KnowledgeContent> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("module_id",dto.getId());
                queryWrapper.in("type",types);
                Integer count = knowledgeContentService.selectCount(queryWrapper);
                dto.setQuestionSum(count);
//                查询知识点名称
                queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("module_id",dto.getId());
                queryWrapper.eq("type",3);
                List<KnowledgeContent> knowledgeContents = knowledgeContentService.queryByCondition(queryWrapper);
                if(knowledgeContents.size() > 0){
//                    String[] knowledgeIds = knowledgeContents.stream().map(KnowledgeContent::getKnowledgeId).toArray(String[]::new);
//                    List<KnowledgeDto> queryKnowledge = queryKnowledge(knowledgeIds);
//                    List<String> names = queryKnowledge.stream().map(KnowledgeDto::getName).collect(Collectors.toList());
                    List<String> names = knowledgeContents.stream().map(KnowledgeContent::getContent).collect(Collectors.toList());
                    dto.setKnowledgeNames(names);
                }
            }
        }

        return  selectPage;
    }

    @Override
    public List queryKnowledgeManager(KnowledgeManagerRequest bean) {
        QueryWrapper qw=new QueryWrapper<KnowledgeManager>();
        //拼装条件
        qw=prepareParams(bean, qw);
        if(!StringUtils.isEmpty(bean.getKnowledgeId())){
            qw.eq("knowledge_id",bean.getKnowledgeId());
        }
        return this.dao.selectList(qw);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(KnowledgeManagerRequest request) {

        KnowledgeManager knowledgeManager = new KnowledgeManager();
        BeanUtils.copyProperties(request,knowledgeManager);
        this.insert(knowledgeManager);

        for (int i = 0; i < request.getKnowledgeIds().size(); i++) {
            String knowledgeId = request.getKnowledgeIds().get(i);
            KnowledgeManagerElementRelation relation = new KnowledgeManagerElementRelation();
            relation.setKnowledgeId(knowledgeId);
            relation.setManageId(knowledgeManager.getId());
            knowledgeManagerElementRelationService.insert(relation);
        }
    }

    @Override
    public void refreshData() {
        QueryWrapper qw=new QueryWrapper<KnowledgeManager>();
        List<KnowledgeManagerElementRelation> newDatas = new ArrayList<>();

        List<KnowledgeManager> list = this.dao.selectList(qw);
        for (int i = 0; i < list.size(); i++) {
            KnowledgeManager knowledgeManager = list.get(i);
            String id = knowledgeManager.getId();
            String knowledgeId = knowledgeManager.getKnowledgeId();
            KnowledgeManagerElementRelation relation = new KnowledgeManagerElementRelation();
            relation.setKnowledgeId(knowledgeId);
            relation.setManageId(id);
            newDatas.add(relation);

            if(newDatas.size() > 999){
                knowledgeManagerElementRelationService.batchInsert(newDatas);
                newDatas = new ArrayList<>();
            }
        }
        if(newDatas.size() > 0){
            knowledgeManagerElementRelationService.batchInsert(newDatas);
        }
    }

    @Override
    public void deleteAllById(KnowledgeManagerRequest request) {
        KnowledgeManager knowledgeManager = this.getById(request.getId());
        if(StringUtils.isEmpty(request.getImportLogIds())){
            this.delete(request.getId());
            deleteQuestionFromLogIds(knowledgeManager.getImportLogIds());
        }else{
            deleteQuestionFromLogIds(request.getImportLogIds());

            String[] logIds = knowledgeManager.getImportLogIds().split("##");
            String[] fileNames = knowledgeManager.getFileNames().split("##");
            StringJoiner logJion = new StringJoiner("##");
            StringJoiner fileJion = new StringJoiner("##");
            for (int i = 0; i < logIds.length; i++) {
                if(!logIds[i].equals(request.getImportLogIds())) {
                    logJion.add(logIds[i]);
                    fileJion.add(fileNames[i]);
                }
            }
            knowledgeManager.setImportLogIds(logJion.toString());
            knowledgeManager.setFileNames(fileJion.toString());
            this.update(knowledgeManager);
        }
    }

    private void deleteQuestionFromLogIds(String importLogIds) {
        if(StringUtils.isEmpty(importLogIds)){
            return;
        }
        String[] logIds = importLogIds.split("##");
        QuestionImportLogRequest logRequest = new QuestionImportLogRequest();
        logRequest.setIds(logIds);
        List<QuestionImportLog> logList = questionImportLogService.queryQuestionImportLog(logRequest);
        List<String> quesitonIdList = new ArrayList<>();
        for (int i = 0; i < logList.size(); i++) {
            QuestionImportLog questionImportLog = logList.get(i);
            String questionIdsStr = questionImportLog.getQuestionIds();
            String[] questionIds = questionIdsStr.split(",");
            quesitonIdList.addAll(Arrays.asList(questionIds));
        }
        String[] ids = quesitonIdList.toArray(new String[0]);
        if(ids.length > 0){
            questionService.batchDelete(ids);
            //日志也删除
            questionImportLogService.batchDelete(logIds);
        }

    }

    private List<KnowledgeDto> queryKnowledge(String[] ids){
        KnowledgeRequest request = new KnowledgeRequest();
        request.setIds(ids);
        return knowledgeService.queryKnowledge(request);
    }

    /**
     * 准备条件
     * @param bean
     * @param qw
     */
    private QueryWrapper prepareParams(KnowledgeManagerRequest bean, QueryWrapper qw) {
        if(bean.getIds()!=null&&bean.getIds().length>0){
            qw.in("id",bean.getIds());
        }
        return qw;
    }

    @Override
    public String queryTemplateIdById(String id) {
        return this.dao.queryTemplateIdById(id);
    }
}
